import { Table, Space, Card, Form, Button, Select, DatePicker, Input, Popover, message } from 'antd'
import { useStore } from '@/store'
import { useEffect, useRef, useState } from 'react'
import { http } from '@/utils'
import { FormOutlined } from '@ant-design/icons'
import { dict_data } from '@/dict'
const { TextArea } = Input
// import { useSocket } from '@/components/SocketProvider'
const { RangePicker } = DatePicker
const OrderList = () => {
    const [form] = Form.useForm()
    const [tabsData, setTabsData] = useState([])
    const tabsDataRef = useRef()
    const { loginStore } = useStore()
    // const [open, setOpen] = useState(false)
    const [params, setParams] = useState({
        userId: loginStore.userId,
        pageNum: 1,
        pageSize: 20
    })
    // const popRef = 
    // const socket = useSocket()
    // socket.onmessage = (message) => {
    //     console.log('message:', message)
    // }
    const [ordersData, setordersData] = useState([])
    const [loading, setLoading] = useState(true)
    const [factorIdListOpt, setFieldsValue] = useState([])
    const [factorListOpt, setFactorListOpt] = useState([])
    const [orderStatusOpt, setOrderStatusOpt] = useState([])
    const [orderMark, setOrderMark] = useState('')


    useEffect(() => {
        const getTabs = async () => {
            const res = await http.post('/alarm/deliversign/getAlarmGroupByUserId', { userId: params.userId })
            const list = res.body.length ? res.body.map(item => ({
                label: item.groupAlarmName,
                value: item.id,
                key: item.id
            })) : [{
                label: '--请选择--',
                value: '',
                key: ''
            }]
            console.log('用户预警组', list)
            setTabsData(list)
            tabsDataRef.current = list
        }
        const getFactorIdList = async () => {
            const res = await http.post('/alarm/deliversign/getAllFreq', { userId: params.userId })
            console.log('周期列表-', res.body)
            const list = res.body.map(item => ({
                value: item.id,
                label: item.freqName
            }))
            setFieldsValue(list)
        }
        const getFactor = async () => {
            const res = await http.post('/alarm/deliversign/getAllFactor')
            console.log('因子列表-', res.body)
            const list = res.body.map(item => ({
                value: item.id,
                label: item.factorName
            }))
            setFactorListOpt(list)
        }
        const getDicfig = async () => {
            const res = await http.post('/alarm/deliversign/getDicConfig', {
                userId: params.userId,
                dictIds: [1009]
            })
            console.log('字典-', res.body)
            setOrderStatusOpt(res.body['1009'].map(item => ({ label: item.dictName, value: item.dictCode })))
            await getTabs()
            await getFactor()
            await getFactorIdList()
            setLoading(false)
        }
        const getList = async () => {
            const res = await http.post('/alarm/deliversign/findOrdersByPage', params)
            const list = res.body.list.map(item => {
                let directionTypeName = '-'
                const requestData = JSON.parse(item.requestData)
                const responseData = JSON.parse(item.responseData)
                const row = {
                    ...item,
                    ...item.tbUserAlarmInfo,
                    ...requestData,
                    ...responseData,
                }
                // 0:Init,初始化; 1:Risking,未风控; 2:Submiting,提交中; 3:Dealing,交易中; 4:PartDeal,部分成交; 5:Deal,全部成交;
                let orderStatusName = row.orderStatus ? dict_data[2000].filter(item => item.dictCode === row.orderStatus)[0].dictName : '-'

                // 交易方向 DirectionType 48 多 49 空 
                // 交易类型 OffsetType 48 买 卖
                // 账号类型 featureType   (2 ETF A股 3 A股) 4 期货 5 港股 6 外盘
                // 是否融资买入卖出 IsCredit 
                switch (row.featureType) {
                    case 2:
                        if (row.DirectionType === 48) { // 多
                            if (row.OffsetType === 48) {// 买
                                directionTypeName = row.IsCredit ? '融资买入' : '买入'
                            }
                        } else if (row.DirectionType === 49) {
                            if (row.OffsetType === 49) {// 卖
                                directionTypeName = row.IsCredit ? '融资卖出' : '卖出'
                            }
                        }
                        break
                    case 3:
                        if (row.DirectionType === 48) { // 多
                            if (row.OffsetType === 48) {// 买
                                directionTypeName = row.IsCredit ? '融资买入' : '买入'
                            }
                        } else if (row.DirectionType === 49) {
                            if (row.OffsetType === 49) {// 卖
                                directionTypeName = row.IsCredit ? '融资卖出' : '卖出'
                            }
                        }
                        break
                    case 4:
                        if (row.DirectionType === 48) { // 多
                            if (row.OffsetType === 48) {// 买
                                directionTypeName = '开多'
                            } else if (row.OffsetType === 49) { // 卖
                                directionTypeName = '平空'
                            }
                        } else if (requestData.DirectionType === 49) {  // 空
                            if (row.OffsetType === 48) {// 买
                                directionTypeName = '开空'
                            } else if (row.OffsetType === 49) { // 卖
                                directionTypeName = '平多'
                            }
                        }
                        break
                    case 5:
                        if (row.DirectionType === 48) { // 多
                            if (row.OffsetType === 48) {// 买
                                directionTypeName = row.IsCredit ? '融资买入' : '买入'
                            }
                        } else if (row.DirectionType === 49) {
                            if (row.OffsetType === 49) {// 卖
                                directionTypeName = row.IsCredit ? '融资卖出' : '卖出'
                            }
                        }
                        break
                    default:
                        break
                }
                row.factorName = row.factorName ? row.factorName : ''
                let groupRow = tabsDataRef.current.filter(citem => citem.value === row.groupId)
                row.groupName = groupRow.length ? groupRow[0].label : ''
                row.direction = row.factorName.indexOf('⬇') !== -1 ? 1 : 0
                row.factorName = row.factorName.replace(/⬇|⬆/g, "")
                row.datetime = row.datetime || row.dateTime
                row.directionTypeName = directionTypeName
                row.orderStatusName = orderStatusName
                // requestData.DirectionType === 48 ? '多' : requestData.DirectionType === 49 ? '空' : '-'
                return row
            })
            console.log('订单列表-', list)
            const total = res.body.total
            setordersData({
                list: list,
                count: total
            })
        }
        if (loading) {
            getDicfig()
        } else {
            getList()
        }
    }, [params, loading])
    const handleOpenChange = (val, data) => {
        const list = [...ordersData.list]
        const row = list.filter(item => item.orderId === data.orderId)[0]
        row.open = val
        setordersData({
            ...ordersData,
            list: list
        })
        setOrderMark(data.orderReason)
    }
    const popRef = useRef()
    const updateOrderReason = (data) => {
        http.post('/alarm/deliversign/updateOrderReason', {
            orderId: data.orderId,
            orderReason: orderMark
        }).then(res => {
            message.success(res.body)
            const list = [...ordersData.list].filter(item => item.orderId === data.orderId)[0].open = false
            setordersData({
                ...ordersData,
                list: list
            })
            setParams({
                ...params
            })
        })
    }
    const columns = [
        { title: '编号', dataIndex: 'orderId', width: 50 },
        {
            title: '品种名称', render: data => {
                return (
                    <Space size="middle">
                        <span>{data.featureName}</span>
                        <span>{data.featureCode}</span>
                    </Space>
                )
            }
        },
        { title: '所属预警组', dataIndex: 'groupName', width: 90 },
        { title: '预警时间', dataIndex: 'datetime', },
        { title: '预警周期', dataIndex: 'freqName', width: 80 },
        { title: '总分', dataIndex: 'score', width: 50 },
        {
            title: '预警因子', dataIndex: 'factorName', render: data => {
                return (
                    <>
                        <span>{data}</span>
                        {
                            data.direction === -1 ?
                                <svg className="icon" aria-hidden="true" style={{ color: '#00E600' }}>
                                    <use xlinkHref="#icon-paixu"></use>
                                </svg> : <svg className="icon" aria-hidden="true" style={{ color: '#FF3232' }}>
                                    <use xlinkHref="#icon-xiangshang"></use>
                                </svg>
                        }
                    </>
                )
            }
        },
        { title: '子账号', dataIndex: 'subAccount', },
        { title: '下单份数', dataIndex: 'amount', width: 80 },
        {
            title: '成交份数', dataIndex: 'realAmount', render: (data) => {
                return <div style={{ minWidth: 80 }}>
                    {data === null ? '-' : data}
                </div>
            }
        },
        {
            title: '报价类型', dataIndex: 'PriceType', render: (data) => {
                return <div style={{ minWidth: 80 }}>
                    {data === 52 ? '对手价' : ''}
                    {data === 53 ? '对手价+一跳' : ''}
                </div>
            }
        },
        { title: '成交价格', dataIndex: 'price', width: 80 },
        { title: '交易类型', dataIndex: 'directionTypeName', width: 80 },
        { title: '下单时间', dataIndex: 'orderTime', },
        {
            title: '交易状态', dataIndex: 'orderStatusName', width: 80, render: data => {
                return (
                    <>
                        <span className={`${data === '全部成交' ? 'success' : ''}`}>{data}</span>
                    </>
                )
            }

        },
        { title: '交易描述', dataIndex: 'orderMark', },
        {
            title: '下单原因备注', render: (data) => {
                return (<>
                    <Space style={{ minWidth: 100 }}>
                        <div>{data.orderReason || '-'}</div>
                        <Popover
                            open={data.open}
                            ref={popRef}
                            onOpenChange={(val) => handleOpenChange(val, data)}
                            content={<>
                                <TextArea
                                    rows={5}
                                    placeholder='请输入下单原因'
                                    style={{ width: 300 }}
                                    value={orderMark}
                                    onChange={(res) => setOrderMark(res.target.value)}
                                />
                                <div style={{ textAlign: 'right', marginTop: 10 }}>
                                    <Button type='primary' size='small' onClick={(e) => updateOrderReason(data)}> 提交</Button>
                                </div>
                            </>} title="编辑下单原因备注" trigger="click">
                            <Button size='small' icon={<FormOutlined />} />
                        </Popover>
                    </Space>
                </>)
            }
        },
    ]
    const onSeach = (values) => {
        const _params = {
            ...values,
            orderStartTime: values.time ? values.time[0].format('YYYY-MM-DD HH:mm:ss') : '',
            orderEndTime: values.time ? values.time[1].format('YYYY-MM-DD HH:mm:ss') : '',
        }
        setParams({
            ...params,
            ..._params,
            pageNum: 1,

        })
    }
    const pageChange = (page, pageSize) => {
        setParams({
            ...params,
            pageSize: pageSize,
            pageNum: page
        })
    }
    return (
        <>
            <Card title="下单记录">
                <Form
                    form={form}
                    onFinish={onSeach}
                    initialValues={{}}
                >
                    <Form.Item style={{ margin: 0 }}>
                        <Form.Item label="预警品种" name="featureName" style={{ display: 'inline-block', width: 240 }}>
                            <Input
                                allowClear
                                placeholder='请输入品种名称'
                                style={{ width: 150 }}
                            />
                        </Form.Item>
                        <Form.Item label="品种代码" name="featureCode" style={{ display: 'inline-block', width: 240 }}>
                            <Input
                                allowClear
                                placeholder='请输入品种代码'
                                style={{ width: 150 }}
                            />
                        </Form.Item>
                        <Form.Item label="所属预警组" name="groupId" style={{ display: 'inline-block', width: 255 }}>
                            <Select
                                onChange={form.submit}
                                style={{ width: 150 }}
                                allowClear
                                placeholder="请选择所属预警组"
                                options={tabsData}
                            />
                        </Form.Item>
                        <Form.Item label="预警周期" name="freqId" style={{ display: 'inline-block', width: 240 }}>
                            <Select
                                maxTagCount={1}
                                mode="multiple"
                                style={{ width: 150 }}
                                allowClear
                                onChange={form.submit}
                                placeholder="请选择预警周期"
                                options={factorIdListOpt}
                                filterOption={(input, option) =>
                                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                }
                            />
                        </Form.Item>
                        <Form.Item label="预警因子" name="factorId" style={{ display: 'inline-block', width: 290 }}>
                            <Select
                                maxTagCount={1}
                                mode="multiple"
                                maxTagTextLength={5} // 最长字符6个
                                style={{ width: 200 }}
                                filterOption={(input, option) =>
                                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                }
                                onChange={form.submit}
                                allowClear
                                placeholder="请选择预警因子"
                                options={factorListOpt}
                            />
                        </Form.Item>
                        <Form.Item label="下单时间" name="time" style={{ display: 'inline-block', width: 370, marginRight: 20 }}>
                            <RangePicker
                                format="YYYY-MM-DD HH:mm"
                                showTime={{
                                    format: 'HH:mm',
                                }}
                            />
                        </Form.Item>
                        <Form.Item label="交易状态" name="orderStatus" style={{ display: 'inline-block', width: 255 }}>
                            <Select
                                style={{ width: 150 }}
                                onChange={form.submit}
                                allowClear
                                placeholder="请选择交易状态"
                                options={orderStatusOpt}
                            />
                        </Form.Item>
                        <Form.Item label="子账号" name="subAccount" style={{ display: 'inline-block', width: 240 }}>
                            <Input
                                allowClear
                                placeholder='请输入子账号'
                                style={{ width: 150 }}
                            />
                        </Form.Item>
                        <Form.Item style={{ display: 'inline-block', width: 100, marginBottom: 10 }}>
                            <Space>
                                <Button type="primary" htmlType="submit">
                                    查询
                                </Button>
                                <Button htmlType="submit">
                                    刷新
                                </Button>
                            </Space>
                        </Form.Item>
                    </Form.Item>
                </Form>
                <Table
                    rowKey="id"
                    size='middle'
                    columns={columns}
                    dataSource={ordersData.list}
                    pagination={
                        {
                            size: 'default',
                            showQuickJumper: true,
                            showSizeChanger: true,
                            pageSize: params.pageSize,
                            onChange: pageChange,
                            showTotal: (total, range) => `共 ${total} 条`,
                            total: ordersData.count,
                            current: params.pageNum
                        }
                    }
                    bordered
                />
            </Card >
        </>
    )
}

export default OrderList